package cate.game.role.mall.refresh.impl;

import cate.game.role.mall.RefreshTimeCheck;
import cate.game.role.mall.refresh.item.RefreshItem;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.commons.lang3.StringUtils;

public interface IFreeRefresh {
    RefreshItem getFreeRefreshItem();

    String getFreeCycle();

    int getFreeTimeMax();

    /** 商店免费刷新重置周期检测 */
    @JsonIgnore
    default void checkFreeCycle() {
        String freeCycle = getFreeCycle();
        int freeTimeMax = getFreeTimeMax();
        // 看看这个商店有没有免费刷新周期
        if (StringUtils.isBlank(freeCycle) || freeTimeMax <= 0) {
            return;
        }
        RefreshItem refreshItem = getFreeRefreshItem();
        if (refreshItem == null) {
            return;
        }
        // 看看剩余免费刷新次数有没有到达上限
        if (refreshItem.getTimes() >= freeTimeMax) {
            return;
        }
        // 计算下一次累计免费刷新次数的时间
        boolean isFirst = refreshItem.lastRefreshTime == 0;
        long nextTime = RefreshTimeCheck.nextRefreshTime(refreshItem.getLastRefreshTime(), freeCycle);
        if (System.currentTimeMillis() > nextTime) {
            refreshItem.updateRefreshItem(nextTime, 1);
            checkFreeCycle();
            if (isFirst) {
                refreshItem.updateRefreshTime(System.currentTimeMillis());
            }
        }
    }

    default boolean hasFreeTimes() {
        return getFreeRefreshItem() != null && getFreeRefreshItem().times > 0;
    }

    default void addFreeTimes(int freeTimes) {
        RefreshItem item = getFreeRefreshItem();
        if (item != null) {
            item.addTimes(freeTimes);
        }
    }

    default void costFreeTimes() {
        RefreshItem item = getFreeRefreshItem();
        if (item != null) {
            if (item.times == getFreeTimeMax()) {
                item.updateRefreshTime(System.currentTimeMillis());
            }
            item.costTimes();
        }
    }
}
